from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from django.db.models import Sum, Count, Q
from django.db.models.functions import TruncMonth
from datetime import date
from rest_framework.permissions import AllowAny

from assets.models import Building, Unit, Device
from users.models import Company, CompanyEmployeeProfile, ParkEmployeeProfile, Visitor
from finance.models import Bill
from services.models import RepairService, CleaningBookingService, WaterDeliveryService, Contract, VisitorAppointmentService
from notification.models import Message

class OverviewStatsAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供园区综合运营总览核心指标。
    """
    def get(self, request, *args, **kwargs):
        # 1. 资产总览
        building_count = Building.objects.count()
        unit_count = Unit.objects.count()
        device_count = Device.objects.count()
        total_parking_spaces = Unit.objects.filter(unit_type='车位').count()
        occupied_parking_spaces = Unit.objects.filter(unit_type='车位', status__in=['已租', '已售']).count()

        # 2. 企业与人员总览
        company_count = Company.objects.count()
        company_employee_count = CompanyEmployeeProfile.objects.count()
        park_employee_count = ParkEmployeeProfile.objects.count()
        total_employee_count = company_employee_count + park_employee_count
        
        # 实时访客统计
        total_visitors = Visitor.objects.count()
        visitors_inside_count = VisitorAppointmentService.objects.filter(status='已入园').count()
        visitors_left_today_count = VisitorAppointmentService.objects.filter(
            status='已离园', 
            expected_visit_time__date=date.today()
        ).count()


        # 3. 核心财务指标 (本月总收入)
        current_month = date.today().month
        current_year = date.today().year
        monthly_revenue = Bill.objects.filter(
            payment_status='已支付',
            payment_date__year=current_year,
            payment_date__month=current_month
        ).aggregate(total=Sum('amount'))['total'] or 0

        # 4. 服务工单总览 (待处理工单)
        pending_repairs = RepairService.objects.filter(status='待受理').count()
        pending_cleaning = CleaningBookingService.objects.filter(status='待受理').count()
        pending_water = WaterDeliveryService.objects.filter(status='待受理').count()
        total_pending_tasks = pending_repairs + pending_cleaning + pending_water

        data = {
            'asset_stats': {'buildings': building_count, 'units': unit_count, 'devices': device_count},
            'people_stats': {
                'companies': company_count, 
                'employees': {
                    'total': total_employee_count,
                    'company_employees': company_employee_count,
                    'park_employees': park_employee_count,
                },
                'visitors': {
                    'total': total_visitors,
                    'inside': visitors_inside_count,
                    'left_today': visitors_left_today_count,
                }
            },
            'parking_stats': {'total': total_parking_spaces, 'occupied': occupied_parking_spaces},
            'finance_stats': {'monthly_revenue': f'{monthly_revenue:,.2f}'},
            'service_stats': {
                'total_pending': total_pending_tasks,
                'breakdown': {
                    'repairs': pending_repairs,
                    'cleaning': pending_cleaning,
                    'water_delivery': pending_water,
                }
            },
        }
        return Response(data)


class UnitStatusDistributionAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供房源状态分布数据。
    """
    def get(self, request, *args, **kwargs):
        status_data = Unit.objects.values('status').annotate(count=Count('status')).order_by('-count')
        # 将status和count重命名为ECharts饼图常用的name和value
        formatted_data = [{'name': item['status'], 'value': item['count']} for item in status_data]
        return Response(formatted_data)


class ContractGrowthTrendAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供近12个月租赁合同增长趋势。
    """
    def get(self, request, *args, **kwargs):
        # 使用 TruncMonth 按月分组计数
        trend_data = Contract.objects.filter(
                contract_type__in=['房源租赁', '车位租赁'],
                sign_date__isnull=False
            ).annotate(
                month=TruncMonth('sign_date')
            ).values('month').annotate(
                count=Count('contract_id')
            ).values('month', 'count').order_by('month')

        # 格式化输出
        formatted_data = [
            {'month': item['month'].strftime('%Y-%m'), 'count': item['count']}
            for item in trend_data
        ]
        return Response(formatted_data)


class CompanyTypeDistributionAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供入驻企业类型分布数据。
    """
    def get(self, request, *args, **kwargs):
        type_data = Company.objects.values('company_type').annotate(count=Count('company_id')).order_by('-count')
        # 将company_type和count重命名为ECharts饼图常用的name和value
        formatted_data = [{'name': item['company_type'], 'value': item['count']} for item in type_data]
        return Response(formatted_data)


class RepairHotspotsAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供报修热点分析（按设备类型）。
    """
    def get(self, request, *args, **kwargs):
        # 关联 repair_service 和 device 表，统计 device.device_type 的出现次数
        hotspot_data = RepairService.objects.exclude(device__isnull=True)\
            .values('device__device_type')\
            .annotate(count=Count('device__device_type'))\
            .values('device__device_type', 'count')\
            .order_by('-count')
        
        # 将 device__device_type 和 count 重命名为更友好的 name 和 value
        formatted_data = [{'name': item['device__device_type'], 'value': item['count']} for item in hotspot_data]
        return Response(formatted_data)


class BuildingStatusAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供园区楼宇类型分布及利用率数据。
    """
    def get(self, request, *args, **kwargs):
        # 使用关联查询和values()进行分组聚合，统计每种楼宇类型的总面积和已占用面积
        building_data = Unit.objects.values('building__building_type').annotate(
            total_area=Sum('actual_area'),
            occupied_area=Sum('actual_area', filter=Q(status__in=['已租', '已售']))
        ).order_by('-total_area')

        # 格式化输出
        formatted_data = [
            {
                'name': item['building__building_type'],
                'total_area': round(item['total_area'] or 0, 2),
                'occupied_area': round(item['occupied_area'] or 0, 2)
            }
            for item in building_data if item['building__building_type']
        ]
        return Response(formatted_data)


class InvestmentTrendAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供近12个月招商（新入驻企业）增长趋势。
    """
    def get(self, request, *args, **kwargs):
        trend_data = Company.objects.filter(
                entry_date__isnull=False
            ).annotate(
                month=TruncMonth('entry_date')
            ).values('month').annotate(
                count=Count('company_id')
            ).values('month', 'count').order_by('month')

        formatted_data = [
            {'month': item['month'].strftime('%Y-%m'), 'count': item['count']}
            for item in trend_data if item['month']
        ]
        return Response(formatted_data)


class AssetSalesLeasingAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供建成楼宇租售情况统计（按面积）。
    """
    def get(self, request, *args, **kwargs):
        # 定义可用于租售的单元类型
        commercial_unit_types = ['办公室', '商铺', '仓库', '厂房']

        # 计算总面积
        total_area_data = Unit.objects.filter(unit_type__in=commercial_unit_types).aggregate(total=Sum('actual_area'))
        total_area = total_area_data['total'] or 0

        # 计算已售面积
        sold_area_data = Unit.objects.filter(unit_type__in=commercial_unit_types, status='已售').aggregate(total=Sum('actual_area'))
        sold_area = sold_area_data['total'] or 0
        
        # 计算已租面积
        leased_area_data = Unit.objects.filter(unit_type__in=commercial_unit_types, status='已租').aggregate(total=Sum('actual_area'))
        leased_area = leased_area_data['total'] or 0

        data = {
            'total_area': round(total_area, 2),
            'sold_area': round(sold_area, 2),
            'leased_area': round(leased_area, 2),
        }
        return Response(data)


class NotificationListAPIView(APIView):
    permission_classes = [AllowAny]
    """
    提供最新的园区通知公告列表(限定类型)。
    """
    def get(self, request, *args, **kwargs):
        notification_types = ['园区公告', '活动推广', '新闻资讯']
        notifications = Message.objects.filter(
            message_type__in=notification_types,
            publish_time__isnull=False
        ).order_by('-publish_time')[:20]

        formatted_data = [
            {
                'id': item.message_id,
                'title': item.title,
                'type': item.message_type,
                'time': item.publish_time.strftime('%Y-%m-%d %H:%M')
            }
            for item in notifications
        ]
        return Response(formatted_data)
